﻿using System.Collections.Concurrent;
using Volo.Abp.DependencyInjection;

namespace FlyingEye.SignalRHubs
{
    public class DeviceResourceMapping : ISingletonDependency
    {
        private readonly ConcurrentDictionary<string, string> _dictionary =
            new ConcurrentDictionary<string, string>();

        private readonly ConcurrentDictionary<string, string> _reverseDictionary = new();

        public int Count => _dictionary.Count;

        public bool TryAdd(string resourceId, string connectionId)
        {
            if (_dictionary.TryAdd(resourceId, connectionId))
            {
                return _reverseDictionary.TryAdd(connectionId, resourceId);
            }
            return false;
        }

        public bool TryGetConnectionId(string resourceId, out string connectionId)
        {
            // TryGetValue 方法是线程安全的，并且尝试获取与指定键关联的值  
            return _dictionary.TryGetValue(resourceId, out connectionId!);
        }

        public bool TryRemoveByConnectionId(string connectionId, out string? clientName)
        {
            if (_reverseDictionary.TryRemove(connectionId, out clientName))
            {
                return _dictionary.TryRemove(clientName, out _);
            }
            return false;
        }
    }
}
